//
//  UIButton+JXBHook.m
//  MobileBank
//
//  Created by Mickey Yin on 2022/3/9.
//

#import "UIButton+JXBHook.h"
#import <objc/runtime.h>

@implementation UIButton (JXBHook)

+ (void)load{
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{

        SEL originalSelector = @selector(sendAction:to:forEvent:);
        SEL swizzledSelector = @selector(jxb_sendAction:to:forEvent:);

        Method originalMethod = class_getInstanceMethod(self.class, originalSelector);
        Method swizzledMethod = class_getInstanceMethod(self.class, swizzledSelector);

        BOOL addMehtod = class_addMethod(self, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));

        if (addMehtod) {
            class_replaceMethod(self, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
            
        } else {
            method_exchangeImplementations(originalMethod, swizzledMethod);
        }
    });
}

- (void)jxb_sendAction:(SEL)action to:(nullable id)target forEvent:(nullable UIEvent *)event {

    [self jxb_sendAction:action to:target forEvent:event];
    
    if ([target isKindOfClass:[NSClassFromString(@"UMSocialShareCancelControl") class]] && sel_isEqual(action, NSSelectorFromString(@"handleShareCancelControl:"))) {
        NSLog(@"--> 分享面板取消按钮");
        // 这里可用通知把事件传出去
        [self registerForNotifications];
    }
}

- (void)registerForNotifications {

    NSNotification *notice = [NSNotification notificationWithName:@"jxbShareCancelBlockNotification" object:nil userInfo:nil];
    //发送消息
    [[NSNotificationCenter defaultCenter] postNotification:notice];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
